import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { FileInfo } from '../types'
import { ProcessStatus } from '../types'
import { watermarkApi } from '../api/watermark'
import { ElMessage } from 'element-plus'

interface FileItem {
  name: string
  size: number
  type: string
  status: ProcessStatus
}

export const useWatermarkStore = defineStore('watermark', () => {
  const files = ref<FileItem[]>([])
  const isProcessing = ref(false)
  const currentFile = ref<FileInfo | null>(null)

  // 添加文件
  const addFile = (file: FileItem) => {
    files.value.push(file)
  }

  // 移除文件
  const removeFile = (index: string) => {
    files.value.splice(parseInt(index), 1)
  }

  // 清空所有文件
  const clearFiles = () => {
    files.value = []
    currentFile.value = null
  }

  // 设置当前处理的文件
  function setCurrentFile(file: FileInfo | null) {
    currentFile.value = file
  }

  // 更新文件状态
  function updateFileStatus(fileName: string, status: ProcessStatus, data?: Partial<FileInfo>) {
    const file = files.value.find(file => file.name === fileName)
    if (file) {
      file.status = status
      if (data) {
        Object.assign(file, data)
      }
    }
  }

  // 处理文件（去除水印）
  const processFile = async (fileName: string) => {
    const fileIndex = files.value.findIndex(file => file.name === fileName)
    if (fileIndex === -1) return

    const fileInfo = files.value[fileIndex]
    
    // 如果已经处理成功，直接返回
    if (fileInfo.status === ProcessStatus.SUCCESS) {
      setCurrentFile(fileInfo as FileInfo)
      return
    }
    
    try {
      // 查找原始文件对象，需要在实际场景中获取，这里简化处理
      const fileInput = document.createElement('input')
      fileInput.type = 'file'
      fileInput.accept = fileInfo.type
      
      // 提示用户选择文件
      ElMessage.info(`请重新选择文件 "${fileInfo.name}" 进行处理`)
      
      fileInput.onchange = async (event) => {
        const input = event.target as HTMLInputElement
        if (!input.files || input.files.length === 0) return
        
        const file = input.files[0]
        
        if (file.name !== fileInfo.name) {
          ElMessage.warning('选择的文件与待处理文件不一致，请重新选择')
          return
        }
        
        isProcessing.value = true
        updateFileStatus(fileName, ProcessStatus.PROCESSING)
        
        try {
          const response = await watermarkApi.removeWatermark(file, (progress) => {
            updateFileStatus(fileName, ProcessStatus.PROCESSING, { progress })
          })
          
          updateFileStatus(fileName, ProcessStatus.SUCCESS, { 
            resultUrl: response.resultUrl
          })
          
          setCurrentFile(files.value[fileIndex] as FileInfo)
          ElMessage.success('水印去除成功')
        } catch (error: any) {
          updateFileStatus(fileName, ProcessStatus.ERROR, { 
            error: error.message || '处理失败'
          })
          ElMessage.error('水印去除失败: ' + (error.message || '未知错误'))
        } finally {
          isProcessing.value = false
        }
      }
      
      fileInput.click()
    } catch (error: any) {
      ElMessage.error('处理失败: ' + (error.message || '未知错误'))
    }
  }

  return {
    files,
    isProcessing,
    currentFile,
    addFile,
    removeFile,
    clearFiles,
    setCurrentFile,
    updateFileStatus,
    processFile
  }
}) 